/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package resources;

import almacen.Almacen;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Homeroe
 */
public class queries {
    static boolean g_use_remote_only = true;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
    
    // Funcion que realiza un query en ambas bases de datos.
    public static PreparedStatement doSyncQuery(Connection cn, PreparedStatement ps, String query){
        String cache = "cache";
        try {
            // Inserta cambios en tabla cache local
            if(g_use_remote_only){cache = "cambios";}
            ps = (PreparedStatement) cn.prepareStatement("INSERT INTO "+cache+"(consulta,tabla) VALUES (?,'ninguno')",Statement.RETURN_GENERATED_KEYS);
            ps.setString(1,query);
            ps.executeUpdate();
            // Ejecuta el query
            ps = (PreparedStatement) cn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
            ps.executeUpdate();
            // En caso de usar 2 bases de datos (Local y remota) ejecuta las acciones en la otra base de datos.
            if(!g_use_remote_only){
                local_connection.setToRemote();
                cn = local_connection.getconnect();
                if(local_connection.local == false){
                    ps = (PreparedStatement) cn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
                    ps.execute();
                    // Guarda el query en la tabla de cambios remota
                    ps = (PreparedStatement) cn.prepareStatement("INSERT INTO cambios(consulta,fecha,tabla) VALUES (?,NOW(),'ninguno')",Statement.RETURN_GENERATED_KEYS);
                    ps.setString(1,query);
                    ps.execute();
                }
                local_connection.setToLocal();
                cn = local_connection.getconnect();
            }
        } catch (SQLException ex) {
almacen.Almacen.logger.log(Level.SEVERE, null, ex);        }
        return(ps);
    }   
}
